const { requireModule } = require('../common/utils.js')
const path = require('path')

const fs = requireModule('fs-extra')
const Service = requireModule('@vue/cli-service/lib/Service.js')

module.exports = class ServiceWrap extends Service {
  async run(name, args = {}, rawArgv = []) {
    // resolve mode
    // prioritize inline --mode
    // fallback to resolved default modes from plugins or development if --watch is defined
    const mode = args.mode || (name === 'build' && args.watch ? 'development' : this.modes[name])

    // --skip-plugins arg may have plugins that should be skipped during init()
    this.setPluginsToSkip(args, rawArgv)


    this.replaceBuildPlugin()

    // load env variables, load user config, apply plugins
    await this.init(mode)

    this.writeLegacyJson();

    args._ = args._ || []
    let command = this.commands[name]
    if (!command && name) {
      error(`command "${name}" does not exist.`)
      process.exit(1)
    }
    if (!command || args.help || args.h) {
      command = this.commands.help
    } else {
      args._.shift() // remove command itself
      rawArgv.shift()
    }
    const { fn } = command
    return fn(args, rawArgv)
  }
  loadEnv(){}

  /**
   * 替换build插件为自定义的
   */
  replaceBuildPlugin(){
    let plugin = this.plugins.find(it => it.id == 'built-in:commands/build')
    plugin.apply = require('./build.js')
  }

  async writeLegacyJson(){
    // bug node_modules\@vue\cli-service\lib\webpack\ModernModePlugin.js 中 applyModule:69 方法 会读取legacy-assets-index.html.json文件如果没有则抛异常

    let tempPath = path.join(this.context, this.projectOptions.outputDir)
    let tempFilename = path.join(tempPath, 'legacy-assets-index.html.json') 

    if (!fs.existsSync(tempFilename)){
      await fs.mkdirp(tempPath)
      await fs.writeFile(tempFilename, '[]')
    }
  }
}